<template>

  <div style="display: flex;">

    <div style="flex-grow: 1">
      <div style="display: flex; align-items: center; justify-content: space-between">
        <h3>分数段统计</h3>
        <el-button type="primary" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
      </div>

      <el-table
        :data="dataList"
        border
        stripe
        style="width: 100%">
        <el-table-column
          prop="title"
          label="分数段"/>
        <el-table-column
          prop="userCount"
          label="用户人数"/>
        <el-table-column
          prop="percent"
          label="百分比%"/>
      </el-table>

    </div>

    <div style="width: 500px; height: 300px">
      <div id="pie-chart" style="width: 500px; height: 300px"/>
    </div>

  </div>

</template>

<script>

import { statScoreRange, statScoreRangeExport } from '@/api/stat/exam'
import * as echarts from 'echarts'

export default {
  name: 'ExamStatRangeScore',
  props: {
    data: Object
  },
  data() {
    return {
      dataList: [],
      chart: null
    }
  },
  watch: {
    data: {
      handler() {
        this.fetchData()
      }
    }
  },

  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      // 加载统计数据
      statScoreRange(this.data).then(res => {
        this.dataList = res.data
        this.initChart()
      })
    },

    // 导出数据
    handleExport() {
      statScoreRangeExport(this.data)
    },

    // 初始化表格
    initChart() {
      const chatData = []
      for (let i = 0; i<this.dataList.length; i++) {
        const item = this.dataList[i]
        const data = { name: item.title, value: item.userCount }
        chatData.push(data)
      }

      const option = {
        tooltip: {
          trigger: 'item',
          // 模板变量有 {a}、{b}、{c}、{d}，分别表示系列名，数据名，数据值，百分比。
          formatter: '{c}人({d}%)'
        },
        series: [
          {
            type: 'pie', // type设置为饼图
            data: chatData
          }
        ]
      }

      this.chart = echarts.init(document.getElementById('pie-chart'))
      this.chart.setOption(option)
    }
  }
}
</script>

<style scoped>
.pass {
  color: #1aac1a
}

.fail {
  color: #ff0000;
}

</style>
